package com.echo.im.client.facade;

import com.echo.im.client.handler.MessageHandler;
import com.echo.im.client.handler.factory.MessageHandlerFactory;
import com.echo.im.client.handler.suport.platform.PlatformMessageHandler;
import com.echo.im.client.status.OnlineStatusService;
import com.echo.im.common.enums.IMTerminalType;
import com.echo.im.common.model.message.platform.PlatformMessage;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;

/**
 *
 * 对外提供统一抽象
 * @author lxy
 * @date 2024-08-14
 */
@Slf4j
@Component
@RequiredArgsConstructor
public class IMClient{

    private final MessageHandlerFactory messageHandlerFactory;
    private final OnlineStatusService onlineStatusService;
    private final List<PlatformMessageHandler<PlatformMessage>> platformMessageHandlerList;

    @Value("${spring.application.name}")
    private String appName;

    public <T> void sendMessage(T message) {
        @SuppressWarnings("unchecked")
        MessageHandler<T> handler = (MessageHandler<T>) messageHandlerFactory.getHandler(message.getClass());
        handler.handleMessage(message);
    }

    /**
     * 判断用户是否在线
     *
     * @param userId 用户id
     */
    public Boolean isUserOnline(Long userId){
        return onlineStatusService.isUserOnline(userId);
    }

    /**
     * 判断多个用户是否在线
     *
     * @param userIds 用户id列表
     * @return 在线的用户列表
     */
    public List<Long> getOnlineUser(List<Long> userIds){
        return onlineStatusService.getOnlineUserIdList(userIds);
    }


    /**
     * 判断多个用户是否在线
     *
     * @param userIds 用户id列表
     * @return 在线的用户终端
     */
    public Map<Long,List<IMTerminalType>> getOnlineTerminal(List<Long> userIds){
        return onlineStatusService.getUserIdTerminalListMap(userIds);
    }

    public void handleAndSendPlatformCmd(PlatformMessage platformMessage) {
        log.info("Handling platform command: {}", platformMessage);
        // 处理平台命令的逻辑
        for (PlatformMessageHandler<PlatformMessage> handler : platformMessageHandlerList) {
            if (handler.support(platformMessage)) {
                handler.sendPlatformCmd(platformMessage);
                break;
            }
        }
    }

}
